package cn.com.freelibra.forum.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import static org.quartz.JobKey.jobKey;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;

import cn.com.freelibra.forum.job.JobMessagQuartzJob;
import cn.com.freelibra.forum.job.ScheduleJob;
import cn.com.freelibra.forum.po.JobSetting;
import cn.com.freelibra.forum.po.User;
import cn.com.freelibra.forum.service.JobSettingService;
import cn.com.freelibra.forum.util.StringUtil;
import cn.com.freelibra.forum.util.constentEnum.AjaxStatus;
import cn.com.freelibra.forum.util.constentEnum.OriginEnum;
import cn.com.freelibra.forum.web.view.AjaxObject;

@Controller
@RequestMapping("/jobMessage")
public class JobController {

	@Resource
	private JobSettingService jobSettingService;

	@Autowired
	private SchedulerFactoryBean schedulerFactoryBean;

	private Map<String, String> urlMap = new HashMap<>();

	private static Integer pageSize = 10;

	@SuppressWarnings("static-access")
	@RequestMapping("/jobManage")
	public String jobManage(Model model, String keyword, Integer pageNum, Integer pageSize) {
		Page<Map<String, Object>> result = jobSettingService.selectJobSettingList(keyword, pageNum, this.pageSize);
		model.addAttribute("result", result);
		model.addAttribute("pageNum", result.getPageNum());
		model.addAttribute("totalPages", result.getPages());
		return "/job/jobManage";
	}
	
	/**
	 * 编辑定时任务
	 * @param request
	 * @return
	 */
	@RequestMapping("/editJob")
	public String editJob(Model model,HttpServletRequest request){
		Integer id = Integer.parseInt(request.getParameter("id"));
		JobSetting jobSetting = jobSettingService.load(id);
		model.addAttribute("jobSetting", jobSetting);
		return "/job/editJob";
	}
	/**
	 * 保存编辑定时任务
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateJob")
	@ResponseBody
	public AjaxObject updateJob(HttpServletRequest request,JobSetting newJobSetting){
		AjaxObject result = new AjaxObject();
		User user = (User)request.getSession().getAttribute("user");
		JobSetting jobSetting = jobSettingService.load(newJobSetting.getId());
		jobSetting.setRunningStatus(newJobSetting.getRunningStatus());
		jobSetting.setLoadRunning(newJobSetting.getLoadRunning());
		jobSetting.setRemarker(newJobSetting.getRemarker());
		jobSetting.setUpdateMan(user.getId().toString());
		jobSetting.setUpdateTime(new Date());
		String cron=request.getParameter("cron");
		jobSetting.setCornExpress(cron);
		jobSettingService.updateJobSetting(jobSetting);
		result.setStatus(AjaxStatus.SUCCESS.getAjaxStatus());// 找不到用户
		result.setMsg("修改成功！");// 提示内容
		result.setAction("alert");// 弹窗提示
		return result;
	}

	@RequestMapping("/jobConfig")
	public String messagePage(Model model) {
		if (urlMap == null || urlMap.size() == 0) {
			for (OriginEnum oe : OriginEnum.values()) {
				urlMap.put(oe.toString(), oe.getOrigin());
			}
		}
		model.addAttribute("urlMap", urlMap);
		return "/job/jobConfig";
	}

	/*
	 * 设定定时任务
	 */
	@RequestMapping("/setUpJob")
	@ResponseBody
	public AjaxObject setUpJob(HttpServletRequest request, JobSetting jobSetting) throws ClassNotFoundException{
		String classImport="cn.com.freelibra.forum.job.JobMessagQuartzJob";
		@SuppressWarnings("unchecked")
		Class<? extends Job> ftClass = (Class<? extends Job>) Class.forName(classImport);
		AjaxObject result = new AjaxObject();
		String cron=request.getParameter("cron");
		if(StringUtil.isEmpty(jobSetting.getJobName())){
			result.setStatus(AjaxStatus.BADREQUEST.getAjaxStatus());// 找不到用户
			result.setMsg("任务名称不能为空！");// 提示内容
			result.setAction("alert");// 弹窗提示
			return result;
		}
		if(StringUtil.isEmpty(cron)){
			result.setStatus(AjaxStatus.BADREQUEST.getAjaxStatus());// 找不到用户
			result.setMsg("执行时间为必填选项！");// 提示内容
			result.setAction("alert");// 弹窗提示
			return result;
		}

		try {
		jobSetting.setCornExpress(cron);
		jobSetting.setTriggerName("jobT");
		jobSetting.setTriggerGroupName("jobTG");
		User user = (User) request.getSession().getAttribute("user");
		jobSetting.setCreateMan(user.getId().toString());
		jobSetting.setCreateTime(new Date());
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		JobDetail jobDetail = JobBuilder.newJob(ftClass)
				.withIdentity(jobSetting.getJobName(), jobSetting.getJobGroupName()).storeDurably().build();
		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(jobSetting.getCornExpress());
		CronTrigger trigger = TriggerBuilder.newTrigger()
				.withIdentity(jobSetting.getJobName(), jobSetting.getJobGroupName()).withSchedule(scheduleBuilder)
				.build();
			scheduler.scheduleJob(jobDetail, trigger);
		} catch (SchedulerException e) {
			jobSettingService.saveSetting(jobSetting);
			result.setStatus(AjaxStatus.BADREQUEST.getAjaxStatus());// 找不到用户
			result.setMsg("设置脚本失败！");// 提示内容
			result.setAction("alert");// 弹窗提示
		}
		jobSettingService.saveSetting(jobSetting);
		result.setStatus(AjaxStatus.SUCCESS.getAjaxStatus());// 找不到用户
		result.setMsg("已成功设置脚本！");// 提示内容
		result.setAction("alert");// 弹窗提示
		return result;
	}

	/*
	 * 立即执行任务
	 */
	@RequestMapping("/immediatelyJob")
	@ResponseBody
	public AjaxObject immediatelyJob(HttpServletRequest request) throws Exception {
		Integer id = Integer.parseInt(request.getParameter("id"));
		JobSetting jobSetting = jobSettingService.load(id);
		AjaxObject result = new AjaxObject();

		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		JobDetail job = JobBuilder.newJob(JobMessagQuartzJob.class)
				.withIdentity(jobSetting.getJobName(), jobSetting.getJobGroupName()).storeDurably().build();
		scheduler.addJob(job, true);
		scheduler.triggerJob(jobKey(jobSetting.getJobName(), jobSetting.getJobGroupName()));
		
		jobSetting.setExecuteTime(new Date());
		jobSettingService.updateJobSetting(jobSetting);
		result.setStatus(AjaxStatus.SUCCESS.getAjaxStatus());// 找不到用户
		result.setMsg("脚本立即执行开始！");// 提示内容
		result.setAction("alert");// 弹窗提示
		return result;
	}

	/*
	 * 定时任务停止操作
	 */
	@RequestMapping("/stopJob")
	@ResponseBody
	public AjaxObject stopJob(HttpServletRequest request) throws Exception {
		Integer id = Integer.parseInt(request.getParameter("id"));
		JobSetting jobSetting = jobSettingService.load(id);
		AjaxObject result = new AjaxObject();

		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		TriggerKey triggerKey = TriggerKey.triggerKey(jobSetting.getTriggerName(), jobSetting.getTriggerGroupName());
		scheduler.pauseTrigger(triggerKey);// 停止触发器
		scheduler.pauseTrigger(triggerKey);// 移除触发器
		JobKey jobKey = JobKey.jobKey(jobSetting.getJobName(), jobSetting.getJobGroupName());
		scheduler.deleteJob(jobKey);// 删除任务

		result.setStatus(AjaxStatus.SUCCESS.getAjaxStatus());// 找不到用户
		result.setMsg("脚本已成功停止！");// 提示内容
		result.setAction("alert");// 弹窗提示
		return result;
	}
	
	/*
	 * 定时任务删除操作
	 */
	@RequestMapping("/removeJob")
	@ResponseBody
	public AjaxObject removeJob(HttpServletRequest request) throws Exception {
		Integer id = Integer.parseInt(request.getParameter("id"));
		JobSetting jobSetting = jobSettingService.load(id);
		AjaxObject result = new AjaxObject();

		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		TriggerKey triggerKey = TriggerKey.triggerKey(jobSetting.getTriggerName(), jobSetting.getTriggerGroupName());
		scheduler.pauseTrigger(triggerKey);// 停止触发器
		scheduler.pauseTrigger(triggerKey);// 移除触发器
		JobKey jobKey = JobKey.jobKey(jobSetting.getJobName(), jobSetting.getJobGroupName());
		scheduler.deleteJob(jobKey);// 删除任务
		
		//删除数据库对应记录
		if(jobSettingService.deleteJobSetting(jobSetting)){
			result.setStatus(AjaxStatus.SUCCESS.getAjaxStatus());// 找不到用户
			result.setMsg("脚本已成功删除！");// 提示内容
			result.setAction("alert");// 弹窗提示
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/setUpJobTest")
	public AjaxObject setUpJobTest(HttpServletRequest request) {
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		// 这里获取任务信息数据
		List<ScheduleJob> jobList = new ArrayList<ScheduleJob>();
		for (int i = 0; i < 3; i++) {
			ScheduleJob job = new ScheduleJob();
			job.setJobId("10001" + i);
			job.setJobName("JobName_" + i);
			job.setJobGroup("dataWork");
			job.setJobStatus("1");
			job.setCronExpression("0/5 * * * * ?");
			job.setDesc("数据导入任务");
			jobList.add(job);
		}
		for (ScheduleJob job : jobList) {
			TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
			// 获取trigger，即在spring配置文件中定义的 bean id="myTrigger"
			CronTrigger trigger = null;
			try {
				trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
			} catch (SchedulerException e1) {
				e1.printStackTrace();
			}
			// 不存在，创建一个
			if (null == trigger) {
				Class<? extends Job> ftClass = null;
				String classImport = "cn.com.freelibra.forum.job.JobMessagQuartzJob";
				try {
					ftClass = (Class<? extends Job>) Class.forName(classImport);
				} catch (ClassNotFoundException e1) {
					e1.printStackTrace();
				}
				JobDetail jobDetail = (JobDetail) JobBuilder.newJob(ftClass)
						.withIdentity(job.getJobName(), job.getJobGroup()).build();
				jobDetail.getJobDataMap().put("scheduleJob", job);
				// 表达式调度构建器
				CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
				// 按新的cronExpression表达式构建一个新的trigger
				trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup())
						.withSchedule(scheduleBuilder).build();
				try {
					scheduler.scheduleJob(jobDetail, trigger);
				} catch (SchedulerException e) {
					e.printStackTrace();
				}
			} else {
				// Trigger已存在，那么更新相应的定时设置
				// 表达式调度构建器
				CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());

				// 按新的cronExpression表达式重新构建trigger
				trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

				// 按新的trigger重新设置job执行
				try {
					scheduler.rescheduleJob(triggerKey, trigger);
				} catch (SchedulerException e) {
					e.printStackTrace();
				}
			}
		}
		/*
		 * String jobName=request.getParameter("jobName"); String
		 * web=request.getParameter("web"); Integer
		 * runningStatus=Integer.parseInt(request.getParameter("runningStatus"))
		 * ; Integer
		 * loadRunning=Integer.parseInt(request.getParameter("loadRunning"));
		 * String cornTime=request.getParameter("cornTime"); String
		 * remarker=request.getParameter("remarker");
		 * 
		 * 
		 * JobDetail jobDetail = new JobDetail(); jobDetail.setJobName(jobName);
		 * jobDetail.setRunningStatus(runningStatus);
		 * jobDetail.setLoadRunning(loadRunning);
		 * jobDetail.setCornTime(cornTime); jobDetail.setRemarker(remarker);
		 * jobDetail.setCreateMan(123l); jobDetail.setCreateTime(new Date());
		 * jobDetailService.saveJobDetail(jobDetail);
		 */

		AjaxObject result = new AjaxObject();
		/*
		 * try { SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
		 * Scheduler sche = gSchedulerFactory.getScheduler(); String job_name =
		 * "动态任务调度"; String clazz = JobClass; //使用Class.forName动态的创建 String cron
		 * = "10 * * * * ?"; //设定时间 QuartzManager.addJob(sche, job_name,
		 * Class.forName(clazz), cron); } catch (Exception e) {
		 * result.setStatus(AjaxStatus.BADREQUEST.getAjaxStatus());
		 * result.setMsg("异常导致,设置脚本失败！");//提示内容 result.setAction("alert");//弹窗提示
		 * return result; }
		 */
		result.setStatus(AjaxStatus.SUCCESS.getAjaxStatus());// 找不到用户
		result.setMsg("已成功设置脚本！");// 提示内容
		result.setAction("alert");// 弹窗提示
		return result;
	}

	
	
	
	public Map<String, String> getUrlMap() {
		return urlMap;
	}

	public void setUrlMap(Map<String, String> urlMap) {
		this.urlMap = urlMap;
	}
}
